<?php

$this->useClass('AggregatedModel_Feed_ReaderItems');

class AggregatedModel_Feed_ReaderForum extends AggregatedModel_Feed_ReaderItems implements AggregatedModel_Feed_FeedInterface
{
	protected function fetch_posts( $q, $page_number, $struct_type ) {
		// извлекает посты по where-части запроса и номеру страницы

		$where = $this->prepare_where_query(
			$this->tag,
			$this->tdis_enum,
			$this->community_oid,
			$this->filter_by_day,
			$this->user_oid,
			$this->filter_by_doctype
		);
		//
		// извлекает посты по where-части запроса и номеру страницы
		$limit = ' limit '.($page_number-1) * $this->page_citems.','.$this->page_citems;

		$order = '';
		switch ($this->order_by) {
		case 'comment_count': $order = "comment_count DESC, odate DESC"; break;
		case 'title':         $order = "allfeed.title, odate DESC"; break;
		default :             $order = "odate DESC "; break;
		}

		$order = $order ? " ORDER BY $order " : '';

		$prefix = $this->rh->ctx->db->db_prefix;

		$sql =
          "SELECT                                                       -- выбираем объекты из allfeed
              {$prefix}objects.*,
              (
                SELECT COUNT(*)
                FROM store_class_comment AS C1
                left join store_objects C2 on C2.oid = C1.oid
                WHERE C1.item_oid = {$prefix}objects.oid
                and C2.is_deleted = 0 and C1.is_deleted = 0
              )
            AS comment_count,                                           -- всего комментов для каждого топика
              (CASE WHEN C.ctime IS NULL THEN {$prefix}objects.ctime ELSE C.ctime END)
            AS odate,                                                   -- дата последнего коммента в топике, или поста если комментов нет
              C.oid
            AS comment_oid,                                             -- oid последнего коммента
              C.text
            AS comment_body,                                            -- текст последнего коммента
              A.oid
            AS poster_oid,                                              -- oid автора последнего коммента
              A.fullname
            AS poster_name,                                             -- имя автора последнего коммента
              CO.community_url
            AS community_url                                            -- URL сообщества
          FROM {$prefix}objects
          INNER JOIN store_class_allfeed AS allfeed ON ({$prefix}objects.oid = allfeed.oid AND allfeed.is_deleted = 0)
          INNER JOIN store_class_community AS CO ON (allfeed.community_oid = CO.oid)
          LEFT JOIN (                                                   -- по одному последнему комменту для каждого топика
            SELECT C.oid,C.text, C.item_oid, C.posted_by_id, O.ctime
            FROM store_class_comment AS C
            INNER JOIN store_objects AS O
            ON C.oid = O.oid
            WHERE O.ctime = (
              SELECT MAX(O2.ctime)
              FROM store_class_comment AS C2
              INNER JOIN store_objects AS O2 ON C2.oid = O2.oid
              WHERE C2.item_oid = C.item_oid
            )) AS C ON C.item_oid = allfeed.oid
          LEFT JOIN store_class_user AS A ON C.posted_by_id = A.oid
					$where"
				." $order"
				." $limit"
				;

		$ors = new DBStoreResult($this->rh->ctx->store, $this->rh->ctx->store->query($sql));

		if (!$ors) { echo "there is no available feed for you"; return false; }

		$cur_date = NULL;
		while ($obj = $ors->next()) {

			$row = $ors->rs->current();
			// найдем автора
			$c['user']['oid']['==']=$obj->data['posted_by_id'];
			$result = $this->rh->ctx->store->find( $c );
			$user = $result->next();
			unset($result, $c);

			$item = array(
				//"type"=>$tdi_types[ $obj->data['tdi_oid'] ],
				'poster'=>array("name"=>$user->data['fullname'],
								"avatar"=>$user->data['avatar'],
								"url"=>$user->id,
								),
				"post"=>array(	"body"=>$obj->data['body'],
								"title"=>$obj->data['title'],
								"url"=>$obj->data['url'],
								"image"=>$obj->data['path'],
								"link"=>$obj->id,
								),
				"ctime"=>RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $row['odate']),
				'comment_count' => $row['comment_count'],
				"community_url"=>$row['community_url'],
				);

			if ($item['comment_count']) {
				$item['last_comment'] = array(
					'poster' => array(
							'oid' => $row['poster_oid'],
							'url' => $row['poster_oid'],
							'name' => $row['poster_name'],
					),
					'oid' => $row['comment_oid'],
					'body' => $row['comment_body'],
					);
			}

			if ($order_by === 'date') {
				$date = $item['ctime'];
				if (($t = $date->format('%Y%m%d')) !== $cur_date) {
					$d = clone($date);
					$item['new_date'] = $d->dayStart();
				}
				$cur_date = $t;
			}
			$items[] = $item;
		}

		return $items;
	}

} // END class
